<template>
  <div
    class="upload-more"
    @mouseenter="mouseenter"
    @mouseleave="mouseleave"
    @paste="e => pasteImg(e, list.length - 1)"
  >
    <ul class="upload-more">
      <li
        v-for="(item, i) in list"
        :key="item[defaultItem.id]"
        :style="{ width: width + 'px', height: width + 'px' }"
        class="upload-more"
      >
        <!-- <input
          :id="$route.name + id + i"
          :ref="i"
          :title="i"
          hidden
          :accept="accept"
          type="file"
          @change="(e)=>{changeImg(e,i)}"> -->
        <div class="upload-info">
          <div class="img-inline-block">
            <div v-if="item.url" class="img_mark">
              <span :style="{ fontSize: width < 70 ? '14px' : '14px' }">
                <!--   <a-icon
                  title="查看"
                  type="eye"
                  :class="width< 100 ? 'mr4': 'mr10'"
                  @click.stop="view(item.url)" />  -->
                <a-popconfirm
                  title="确定删除?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="del(i)"
                >
                  <a-icon
                    style="color: red; pointer-events: all"
                    title="删除"
                    type="delete"
                  />
                </a-popconfirm>
              </span>
            </div>
            <img
              v-if="item.url"
              :style="{
                maxWidth: width * 0.85 + 'px',
                maxHeight: width * 0.85 + 'px'
              }"
              :src="item.url"
              alt=""
              @click.stop="view(item.url)"
            />
          </div>
          <a-progress
            v-if="!item.url && item.percent"
            type="circle"
            :percent="item.percent || 0"
            :width="width * 0.8"
          />
          <a-icon v-if="!item.url && !item.percent" class="fs20" type="plus" />
          <p v-if="width > 80 && !item.url && !item.percent">Upload</p>
        </div>
      </li>
      <li
        v-if="list.length < maxLength"
        :style="{ width: width + 'px', height: width + 'px' }"
        class="upload-more"
        @click="upload"
      >
        <div class="upload-info">
          <a-icon type="plus" />
          <p v-if="width > 80">Upload</p>
        </div>
      </li>
    </ul>

    <!-- v-if="dragable" -->
    <a-modal
      v-model="visible"
      title="图片预览"
      :z-index="9999"
      :footer="null"
      width="600px"
    >
      <div>
        <img ref="img" style="width: 560px" :src="viewImg" alt="" />
      </div>
    </a-modal>
    <input
      v-for="i in maxLength"
      :id="$route.name + 'a' + id + i"
      :key="i"
      :accept="accept"
      hidden
      type="file"
      @change="
        e => {
          load(e, list.length - 1)
        }
      "
    />
    <div style="z-index: -1" class="d-relative">
      <input ref="inputText" class="d-absolute" type="text" />
    </div>
    <viewImage v-if="false" />
  </div>
</template>
<script>
import axios from 'axios'
import viewImage from '@/components/uploadImg/viewImage'
export default {
  components: { viewImage },
  props: {
    affix: {
      type: Boolean,
      default: false
    },
    width: {
      type: Number,
      default: 100
    },
    imgSize: {
      type: Number,
      default: 10
    },
    maxLength: {
      type: Number,
      default: 1
    },
    defaultItem: {
      type: Object,
      default: function () {
        return { url: 'url', id: 'id', item: '', name: 'name' }
      }
    },
    value: {
      type: String,
      default: ''
    },
    imgList: {
      type: Array,
      default: () => []
    },
    accept: {
      type: String,
      default: '*'
    },
    uploadUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      random: Math.random(),
      headers: {
        'Content-Type': 'multipart/form-data',
        token: localStorage.userId,
        accountId: localStorage.accountId
      },
      id: parseInt(Math.random() * 10000).toString(36),
      visible: false,
      viewImg: '',
      // current: 0,
      percent: 0,
      url: ''
    }
  },
  computed: {
    list() {
      return this.getList()
    }
  },
  methods: {
    upload() {
      document
        .getElementById(
          this.$route.name + 'a' + this.id + (this.imgList.length || 1)
        )
        .click()
      // }
    },
    getList() {
      return this.imgList || []
    },
    // uploadImg (i) {
    //   this.current = i
    //   document.getElementById(this.$route.name + this.id + i).click()
    // },
    del(i) {
      this.imgList.splice(i, 1)
    },
    view(img) {
      this.viewImg = img

      // var reg = new RegExp('Compress', 'g')
      // img = img?.replace(reg, '')
      img = img?.replace(/(.*)Compress/, '$1')

      if (this.affix) {
        this.$emit('view', img)
      } else {
        this.visible = true
      }
    },
    mouseleave() {
      this.$refs.inputText.blur()
    },
    mouseenter() {
      console.log(333)
      this.$refs.inputText.click()
      this.$refs.inputText.focus()
    },
    pasteImg(e, i) {
      console.log(e, i, 22222222)
      const clipboardData = e.clipboardData || window.clipboardData
      console.log(clipboardData) // 查看clipboardData
      const items = clipboardData.items
      const types = clipboardData.types
      console.log(items, types)
      let file = null
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        console.log(items[i])
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile()
          // break
        } else {
          // clipboardData.clearData(items[i].type)
          var str = clipboardData.getData(items[i].type)
          console.log(str)
        }
      }
      console.log(file)
      if (!file) {
        this.$message.error('请粘贴图片')
        return
      }
      this.uploadAjax(file, e)
    },
    // changeImg (e, i) {
    //   this.$set(this.imgList[i], 'url', '')
    //   this.$set(this.imgList[i], 'percent', 0.1)
    //   const size = e.target.files[0].size
    //   const fileName = e.target.files[0].name
    //   if (this.accept !== '*' && !this.accept.includes(fileName.split('.')[fileName.split('.').length - 1].toLowerCase())) {
    //     this.$message.error(`只支持${this.accept}文件格式`)
    //     return
    //   }
    //   if (size / 1024 / 1024 > this.imgSize) {
    //     this.$message.error(`文件大小不能超过${this.imgSize}M`)
    //     return
    //   }
    //   const self = this
    //   const file = e.target.files[0]
    //   const formData = new FormData()
    //   formData.append('file', file)
    //   axios({

    //     url: localStorage.cpsurlimg || this.uploadUrl || process.env.VUE_APP_FILE || 'https://scm-develop.kapeixi.cn/oss/uploadFileToOss',
    //     method: 'post',
    //     onUploadProgress: function (progressEvent) { // 原生获取上传进度
    //       if (progressEvent.lengthComputable) {
    //         self.imgList[i].percent = parseInt(progressEvent.loaded / progressEvent.total * 100) < 100 ? parseInt(progressEvent.loaded / progressEvent.total * 100) : 99
    //       }
    //     },
    //     headers: {
    //       'Content-Type': 'multipart/form-data',
    //       userId: localStorage.userId,
    //       token: localStorage.userId,
    //       Authorization: localStorage.token,
    //       tokenSign: 2
    //     },
    //     data: formData
    //     //    withCredentials: true 指定域名
    //   }).then(res => {
    //     e.target.value = ''
    //     Object.assign(self.imgList[i], { name: fileName, url: res.data.data.ossUrl })
    //     self.imgList[i].percent = 0
    //   })
    // },
    load(e, i) {
      console.log(i)
      const file = e.target.files[0]
      this.uploadAjax(file, e)
    },
    uploadAjax(file, e) {
      if (this.list.length >= this.maxLength) {
        this.$message.error(`最多上传${this.maxLength}张图片`)
        return false
      }
      const size = file.size
      const fileName = file.name
      if (
        this.accept !== '*' &&
        !this.accept.includes(
          fileName.split('.')[fileName.split('.').length - 1].toLowerCase()
        )
      ) {
        this.$message.error(`只支持${this.accept}文件格式`)
        return
      }
      if (size / 1024 / 1024 > this.imgSize) {
        this.$message.error(`文件大小不能超过${this.imgSize}M`)
        return
      }
      const self = this
      // const file = e.target.files[0]
      const formData = new FormData()
      this.percent = 1
      formData.append('file', file)
      const item = { name: fileName, url: '', id: Date.now(), percent: 0.01 }
      self.imgList.push(item)
      axios({
        url:
          localStorage.cpsurlimg ||
          this.uploadUrl ||
          process.env.VUE_APP_FILE ||
          'https://scm-develop.kapeixi.cn/oss/uploadFileToOss',
        method: 'post',
        onUploadProgress: function (progressEvent) {
          // 原生获取上传进度
          if (progressEvent.lengthComputable) {
            item.percent =
              parseInt((progressEvent.loaded / progressEvent.total) * 100) < 100
                ? parseInt((progressEvent.loaded / progressEvent.total) * 100)
                : 99
            // self.percent = parseInt(progressEvent.loaded / progressEvent.total * 100) < 100 ? parseInt(progressEvent.loaded / progressEvent.total * 100) : 99
          }
        },
        headers: {
          'Content-Type': 'multipart/form-data',
          userId: localStorage.userId,
          token: localStorage.userId,
          Authorization: localStorage.token,
          tokenSign: 2,
          accountId: localStorage.accountId
        },

        data: formData
        //    withCredentials: true 指定域名
      }).then(res => {
        e.target.value = ''
        item.url = res.data.data.ossUrl
        // self.imgList[i+1].url = res.data.data.url
        // self.imgList.push({name:fileName,url:res.data.data.url,id:Date.now(),percent:100})
        self.percent = 0
      })
    }
  }
}
</script>
<style lang="less" scoped>
ul {
  padding-left: 0;
  margin: 0;
}
li {
  list-style-type: none;
  // width: 100px;
  // height: 100px;
  border: 1px dashed #999;
  background: #fafafa;
  margin-right: 10px;
  overflow: hidden;
  text-align: center;
  margin-bottom: 10px;
  border-radius: 3px;
  &:hover {
    border: 1px dashed #1989fa;
  }
}
.upload-more {
  display: inline-block;
  & /deep/ .anticon-plus {
    font-size: 20px;
  }
}
.upload-info {
  display: flex;
  align-items: center;
  flex-direction: column;
  height: 100%;
  justify-content: center;
  opacity: 0.7;
  cursor: pointer;
  padding: 5px;
  & > img {
    min-width: 50px;
    transition: all 0.5s;
  }
  p {
    margin-top: 5px;
  }
}
.img-inline-block {
  position: relative;
  width: 100%;
  height: 100%;
  & > div {
    pointer-events: none;
    color: #999;
    font-size: 20px;
    position: absolute;
    // background: rgba(0, 0, 0, 0.3);
    width: 100%;
    height: 100%;
    z-index: 2;
    cursor: pointer;
    & > span {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
  img {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto !important;
  }
}
</style>
